package network;


import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.net.SocketException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UdpDicServer extends UdpEchoServer{
    public UdpDicServer(int port) throws SocketException {
        super(port);
    }

    public String process(String request) throws SQLException {
        return dict(request);
    }
    public String dict(String request) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&serverTimezone=GMT&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        Connection connection = dataSource.getConnection();
        String sql  = "select chinese from dict where english = ? ;";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,request);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            return resultSet.getString("chinese");
        }
        resultSet.close();
        statement.close();
        connection.close();
        return request+"：字典中没有该词";
    }

    public static void main(String[] args) throws IOException, SQLException {
        UdpDicServer server = new UdpDicServer(9090);
        server.start();
    }
}
